import soapp
import Kingfisher
import AsyncDisplayKit


extension UIImage{
    public convenience init?(share_named:String) {
        
//        NSBundle *bundle = [NSBundle bundleForClass:[TZImagePickerController class]];
//           NSURL *url = [bundle URLForResource:@"TZImagePickerController" withExtension:@"bundle"];
//           bundle = [NSBundle bundleWithURL:url];
        
//        if let path = Bundle.path(for: MoShare.self, bundleName: "Share", fileName: MoLocalizable.lproj, type: "lproj"){

        
        
//        let b = Bundle(for: MoShare.self)
//        if let url = b.url(forResource: "mosdk-Share", withExtension: "bundle"){
//            let bundle = Bundle(url: url)
//            print("++++++S\(bundle)")
//
//            self.init(named: share_named, in: bundle, compatibleWith: nil)
//            print("++++\(self)")
//        }else{
//            print("++++:===")
//            self.init(named: share_named, in: Bundle(for: MoShare.self), compatibleWith: nil)
//        }
//


        
        if let path = Bundle(for: MoShare.self).path(forResource: "mosdksShare", ofType: "bundle"){
            if let bundle = Bundle(path: path){
                self.init(named: share_named, in: bundle, compatibleWith: nil)
            }
            else{
                self.init(named: share_named, in: Bundle(for: MoShare.self), compatibleWith: nil)
            }
        }else{
            self.init(named: share_named, in: Bundle(for: MoShare.self), compatibleWith: nil)
        }
//
        
    }
}

public protocol MoImageResouce {
    var imageResource:Any{get}
}



extension UIImage:MoImageResouce{
    public var imageResource: Any{
        get{
            return self
        }
    }
}
extension String:MoImageResouce{
    public var imageResource: Any{
        get{
            return self
        }
    }
}

public protocol MoShareRealization {
    func share(media:MoShare.Media,sence:MoShare.Scene,callBack:ShareCallBack?)
    var plat:String{get set}
}

public class ShareQute:NSObject{
    let title:String
    let icon:MoImageResouce
    let link:String
    let image:MoImageResouce?
    let desc:String?
    public var wxMiniprogram:WXMiniProgramObject? = nil
    
    
    
    let imgV = UIImageView()
    public init(title:String,icon:MoImageResouce,link:String,image:MoImageResouce?=nil,desc:String?=nil,miniprogram:WXMiniProgramObject?=nil) {
        self.title = title
        self.icon = icon
        self.link = link
        self.image = image
        self.desc = desc
        super.init()
        self.wxMiniprogram = miniprogram
        load(icon: icon)
    }
    
    var iconImage:UIImage? = nil
    static var holder = UIImage.image(UIColor.table_bg_color, size: [100,100])
    func load(icon:MoImageResouce) {
        weak var wself = self
        if let url = icon as? String{
            
//            if let img = UIImage.kf_cache(url:url){
//                iconImage = img
//                return
//            }
        
            let lineurl = URL(string: url)
                imgV.kf.setImage(with: lineurl, placeholder: nil, options: [.transition(ImageTransition.fade(0))], progressBlock: nil) { (result) in
                    switch result{
                    case .success(let r):
                        if let _img = r.image.commpress(width: 240){
                            wself?.iconImage = _img
                        }
                        break
                    case .failure:
                        wself?.iconImage = ShareQute.holder
                }
            }
        }
        if let img = icon as? UIImage{
            iconImage = img
        }else{
            iconImage = ShareQute.holder
        }
    }
}
 

public class MoAction{
    public let icon:UIImage?
    public let name:String
    public var action:(_:NSMutableDictionary)->Void = {_ in}
    
    public init(icon:UIImage?,name:String,action:@escaping (_:NSMutableDictionary)->Void) {
        self.icon = icon
        self.name = name
        self.action = action
    }
}

public class MoShare{
    public init() {
        
    }
    @discardableResult
    public func plats(_ plats:[[String:Any]]) -> MoShare {
        _plats = plats
        return self
    }
    
    @discardableResult
    public func actions(_ actions:[[String:Any]]) -> MoShare {
        _actions = actions
        return self
    }
    @discardableResult
    public func append(plats:[[String:Any]]) -> MoShare {
        _plats = _plats + plats
        return self
    }
    
    @discardableResult
    public func append(actions:[[String:Any]]) -> MoShare {
        _actions = _actions + actions
//        print("++++IIIII|\(_actions)")
        return self
    }
    @discardableResult
    public func clicked(_ click:@escaping ItemClick) ->MoShare{
        _clicked = click
        return self
    }
    @discardableResult
    public func object(_ obj:NSMutableDictionary) -> MoShare {
        _object = obj
        return self
    }
    @discardableResult
    public func finish(_ block:ShareCallBack?) -> MoShare {
        _finish = block
        return self
    }
    @discardableResult
    public func qute(_ qute:ShareQute)->MoShare{
        _qute = qute
        var info = NSMutableDictionary()
        info["title"] = _qute.title
        info["icon"] = _qute.icon
        info["link"] = _qute.link
        if let image_ = _qute.image{
            info["image"] = image_
        }
        if let desc_ = _qute.desc{
            info["desc"] = desc_
        }
        if let wxMiniprogram = _qute.wxMiniprogram{
            info["wxMiniprogram"] = wxMiniprogram
        }
        shareInfo = info
        MoShare._default = self
        return self
    }
    
    var _clicked:ItemClick = {_ in return true}
    var _plats:[[String:Any]] = SharePanel.Setting.shareItems
    var _actions:[[String:Any]] = SharePanel.Setting.actionItems
    var _object:NSMutableDictionary = [:]
    var _finish:ShareCallBack? = nil
    var _qute:ShareQute = .init(title: "", icon: "", link: "")
//    var shareCallBack:ShareCallBack? = nil
    
    public var shareInfo:NSMutableDictionary = NSMutableDictionary()
    static public func add(plat:MoShareRealization) {
        var have = false
        for r in realizations {
            if r.plat == plat.plat{
                have = true
            }
        }
        if !have{
            realizations.append(plat)
        }
    }
    static public func getPlat(plat:String) -> MoShareRealization? {
        for e in realizations {
            if e.plat == plat{
                return e
            }
        }
        return nil
    }
    
    public static var realizations:[MoShareRealization] = []
    public enum Scene:Int {
        case session = 0
        case timeLine = 1
        case favorite = 2
        case specifiedSession = 3
        
//        WXSceneSession          = 0,   /**< 聊天界面    */
//        WXSceneTimeline         = 1,   /**< 朋友圈     */
//        WXSceneFavorite         = 2,   /**< 收藏       */
//        WXSceneSpecifiedSession = 3,   /**< 指定联系人  */
    }
    
    public enum Media {
        case image(title:String,desc:String,thumb:MoImageResouce?,image:MoImageResouce?)
        case video(title:String,desc:String,thumb:MoImageResouce?)
        case music(title:String,desc:String,thumb:MoImageResouce?,url:String)
        case webpage(title:String,desc:String,thumb:MoImageResouce?,url:String)
        case wxProgram(title:String,desc:String,thumb:MoImageResouce?,program:WXMiniProgramObject)

    }

    static var _default:MoShare? = nil
    public static var `default`:MoShare{
        get{
            guard let share = _default else {
                let share = MoShare()
                _default = share
                return share
            }
           return share
        }
    }
    public func share(title:String,icon:MoImageResouce,link:String,image:MoImageResouce?=nil,desc:String?=nil,callBack:ShareCallBack?=nil){
       
    }
    public func show() {
        
        var info = NSMutableDictionary()
        info["title"] = _qute.title
        info["icon"] = _qute.icon
        info["link"] = _qute.link
        if let image_ = _qute.image{
            info["image"] = image_
        }
        if let desc_ = _qute.desc{
            info["desc"] = desc_
        }
        if let wxMiniprogram = _qute.wxMiniprogram{
            info["wxMiniprogram"] = wxMiniprogram
        }
        let panel = SharePanel()
        panel.from = self
        shareInfo = info
        MoShare._default = self
        panel.share(info)
    }
    
    public func share(plat:String,media:Media,sence:Scene,callBack:ShareCallBack?){

        if let rezliz = MoShare.getPlat(plat: plat){
            rezliz.share(media: media, sence: sence, callBack: callBack)
        }
       
    }
}

public typealias ItemClick = (_:NSMutableDictionary) -> Bool

public typealias ShareCallBack = (_:Bool,_:String,_:MoShare.Media?,_:MoShare.Scene?)->Void


extension MoShare{
    
    
//    static var holder = UIImage.image(UIColor.table_bg_color, size: [100,100])
//    static var defaultImg = UIImage.image(UIColor.table_bg_color, size: [100,100])
//    static let shareImgV = UIImageView()
//    static var itemClick:ItemClick? = nil
//    class func refreshIcon(icon:MoImageResouce) {
//        if let url = icon as? String{
//            if let img = UIImage.kf_cache(url:url){
//                defaultImg = img
//                return
//            }
//            let lineurl = URL(string: url)
//                MoShare.shareImgV.kf.setImage(with: lineurl, placeholder: nil, options: [.transition(ImageTransition.fade(0.1))], progressBlock: nil) { (result) in
//                    switch result{
//                    case .success(let r):
//                        if let _img = r.image.commpress(width: 240){
//                            defaultImg = _img
//                        }
//                        break
//                    case .failure:
//                        defaultImg = holder
//                }
//            }
//        }
//        if let img = icon as? UIImage{
//            defaultImg = img
//        }else{
//            defaultImg = holder
//        }
//    }
}


public enum SharePlatform:Int{
    
    case wx_friend = 0
    case wx_pengyquan = 1
    case qq_friend = 2
    case qq_zone = 3
    case sina = 4
    
    case copy_link = 20
    

    public func share(from:MoShare) {
        let obj = from.shareInfo
        let title = obj["title",""]
        let link = obj["link",""]
        let content = obj["desc",""]
        let icon = from._qute.icon
//        print("______SKKKS",obj)
        switch self.rawValue {
        case 0:
            if let wxMiniprogram = obj["wxMiniprogram"] as? WXMiniProgramObject {
                MoToast.share.do(mode: .success("wx"))
                from.share(plat: "WX", media: .wxProgram(title: title, desc: content, thumb: icon, program: wxMiniprogram), sence: .timeLine, callBack: nil)
            }else{
                from.share(plat: "WX", media: .webpage(title: title, desc: content, thumb: icon, url: link), sence: .session, callBack: nil)
            }
          
        case 1:
            if let wxMiniprogram = obj["wxMiniprogram"] as? WXMiniProgramObject {
                MoToast.share.do(mode: .success("wx"))
                from.share(plat: "WX", media: .wxProgram(title: title, desc: content, thumb: icon, program: wxMiniprogram), sence: .timeLine, callBack: nil)
            }
            else{
                from.share(plat: "WX", media: .webpage(title: title, desc: content, thumb: icon, url: link), sence: .timeLine, callBack: nil)
            }
//

        default:
            break
        }
//        MEShareCenter.default().shareWebInfo(withPlatformIndex: self.rawValue)
    }
}
